#include <stdio.h>
#include <sys/types.h>         
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <unistd.h>



int main(int argc, char ** argv)
{
	printf("-----Serveur-----\n");
	if (argc != 2) {
         printf("Erreur: pas de port en parametre\n");
         exit(0);
    }
    int port = atoi(argv[1]);
    printf("port =%d\n",port);
    int i;
    struct sockaddr_in p = { 0 };
    struct sockaddr_in clientaddr = {0};
	int sock = socket(AF_INET,SOCK_STREAM,0);
	if (sock < 0) 
	{
        printf("Erreur dans l'ouverture de la socket\n'");
        exit(0);
    }
    p.sin_family = AF_INET;
    p.sin_port = htons(port);
    p.sin_addr.s_addr = htonl(INADDR_ANY);
    for(i=0;i<8;i++){
		   p.sin_zero[i] = 0;
	}
	int mybind = bind(sock, (struct sockaddr* ) &p,sizeof(p));
	if(mybind < 0)
	{
		 printf("Erreur dans le bind\n'");
         exit(1);
	}
	
	int lis = listen(sock,3);
	if(lis < 0 )
	{
		printf("Erreur dans le listen\n'");
        exit(1);
	}
	int clientlen = (socklen_t)sizeof(clientaddr);
	while(1)
	{
		int acc = accept(sock,(struct sockaddr *)&clientaddr, &clientlen);
		if(acc < 0){
			printf("Erreur dans le accepte\n'");
			exit(1);
		}
		int f = fork();
		if(f == 0) // fils
		{
			char  var[255] = { 0 } ;
			printf("Serveur connecte à  %d \n", acc);
			
			int i = read(acc,var,sizeof(var));
			printf("read =  %d\n",i);
			printf("var =  %s\n",var);
			
			close(acc);
		}
	}
	
	
	
	
	
	
	
	
	
	
	
}
